import configparser
import json
import sys
import traceback

import requests

sys.path.append("/netboxSyncZabbix")
from api import zabbix_api6, weixin_webhook

from loguru import logger

import os

logger.add("/var/log/Task/create_user/Create_user.log", rotation="00:00", backtrace=True, diagnose=True, level="DEBUG")

# 获取配置文件
dir_name = os.path.dirname(os.path.dirname(__file__))
ini_path = f"{dir_name}/config.ini"

# config = configparser.ConfigParser()
config = configparser.RawConfigParser()
config.read(ini_path)

# 关联脚本变量
netbox_url = config.get("netbox", "url")
netbox_token = config.get("netbox", "token")
limit = config.get("netbox", "limit")
verify = config.getboolean("netbox", "verify")
zabbix_server_url = config.get("zabbix", "url")
zabbix_user = config.get("zabbix", "user")
zabbix_passwd = config.get("zabbix", "passwd")
webhook_test = config.get("global", "webhook_test")
# webhook_url = config.get("global", "webhook_url")
father_template_group = config.get("global", "father_template_group")
proxy01_id = config.get("zabbix", "proxy01_id")
sre_zabbix_server_url = config.get("zabbix", "sre_url")
sre_zabbix_user = config.get("zabbix", "sre_user")
sre_zabbix_passwd = config.get("zabbix", "sre_password")

# zabbix_server_url = config.get('zabbix_test', "url")
# create_username = config.get("zabbix_test", "create_username")
create_username = config.get("zabbix", "create_username")
# create_password = config.get("zabbix_test", "create_password")
create_password = config.get("zabbix", "create_password")

rbacx_url = config.get("rbacx", "url")
# rbacx_url = config.get("rbacx", "test_url")
# zabbix_read_role_id = config.get("zabbix_test", "read_role_id")
zabbix_read_role_id = config.get("zabbix_test", "read_role_id")
# zabbix_admin_role_id = config.get("zabbix_test", "admin_role_id")
zabbix_admin_role_id = config.get("zabbix_test", "admin_role_id")


def sync_user_to_zabbix():
    error_list = []
    try:
        # 获取 zabbix token
        token = zabbix_api6.zabbix_get_token(create_username, create_password, zabbix_server_url, verify)

        # 获取用户列表
        # get_user_url = "http://rbacx.devops.xiaohongshu.com/rbacx/rest/api/list/user/code/Network-Read?="
        get_role_url = rbacx_url + "list/role"
        header = {
            'Content-Type': 'application/json',
            'accept': 'application/json',
            "app-token": "it-zabbix",
            "app-name": "it-zabbix",
        }
        role_list_info = requests.get(url=get_role_url, headers=header)
        role_list = json.loads(role_list_info.text)["data"]
        logger.info(f"全部角色列表：{role_list}")

        for role in role_list:
            logger.info(f"本次检查角色：{role}")
            if role["code"].split("-")[-1] == "Read":
                zabbix_role_id = zabbix_read_role_id
            elif role["code"].split("-")[-1] == "Admin":
                zabbix_role_id = zabbix_admin_role_id

            get_user_url = rbacx_url + f"list/user/code/{role['code']}?="
            user_list_info = requests.get(url=get_user_url, headers=header)
            user_list = json.loads(user_list_info.text)["data"]
            logger.info(f"全部用户列表：{user_list}")
            for user in user_list:
                logger.info(f"本次检查用户：{user}")
                username = user["email"].split("@")[0]

                # 获取用户组id
                group_info = zabbix_api6.zabbix_get_usergroup(token, zabbix_server_url, "name", role["code"], "0")
                if group_info:
                    group_id = group_info[0]["usrgrpid"]
                    # 创建用户
                    create_info = zabbix_api6.create_user(token, zabbix_server_url, username, zabbix_role_id, group_id)
                    if create_info.get("error"):
                        if create_info["error"]["data"] == f'User with username "{username}" already exists.':
                            # 获取用户信息
                            user_info = zabbix_api6.zabbix_get_user(token, zabbix_server_url, "username", username)
                            user_id = user_info["result"][0]["userid"]

                            # 获取用户所在组信息
                            # user_group_info = zabbix_api6.zabbix_get_user_group(token, zabbix_test_url, "selectUsers", {"userid": user_id})
                            user_group_info = zabbix_api6.zabbix_get_user_group(token, zabbix_server_url, "selectUsers",
                                                                                {"userid": user_id})

                            group_list = []
                            group_power = {"usrgrpid": group_id}
                            for user_group in user_group_info["result"]:
                                if {"userid": user_id} in user_group["users"]:
                                    group_dict = {"usrgrpid": user_group["usrgrpid"]}
                                    if group_dict not in group_list and user_group["usrgrpid"] != group_id:
                                        group_list.append(group_dict)
                            logger.info(f"用户原有组：{group_list}")
                            group_list.append(group_power)

                            # 修改用户所属组
                            update_user_info = zabbix_api6.zabbix_update_user(token, zabbix_server_url, user_id,
                                                                              "usrgrps",
                                                                              group_list)
                            print(update_user_info)
                            print("---------同步成功--------")
                        else:
                            logger.error(f"创建用户失败，用户名：{username},报错信息:{create_info['error']}")
                            error_list.append({"username": username, "power": role["code"]})
                    else:
                        logger.info(f"创建用户成功，用户名：{username}")
        return error_list
    except Exception:
        logger.error(f"用户同步失败， 报错信息：{traceback.format_exc()}")
        return error_list


if __name__ == '__main__':
    error_list = sync_user_to_zabbix()
    if error_list:
        content = f"## zabbix 用户同步失败报告: \n"
        for error in error_list:
            file = f"用户名：{error['username']},申请{error['power']} 失败"
            content += file
        logger.error(f'zabbix 同步用户失败报告: {content}')
        response = weixin_webhook.send_to_webhook(webhook_test, content)
